package com.ytx.flutter_ytx_plugin.x5

import android.content.Context
import android.os.Bundle
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsListener
import com.tencent.smtt.sdk.TbsVideo
import com.ytx.flutter_ytx_plugin.X5Response
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext


/**
 * @author :  huangzhen
 * date    :  2023/12/18
 * describe:  android
 */

object X5ApiHandler : CoroutineScope {

    fun setup(context: Context?, x5Response: X5Response ) {
        val map = hashMapOf<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.setTbsListener(object : TbsListener {
            override fun onDownloadFinish(p0: Int) {
                launch {
                    withContext(Dispatchers.Main) {
                        x5Response.onDownloadFinish(p0.toLong()) {}
                    }
                }
            }

            override fun onInstallFinish(p0: Int) {

                launch {
                    withContext(Dispatchers.Main) {
                        x5Response.onInstallFinish(p0.toLong()) {
                        }
                    }
                }

            }

            override fun onDownloadProgress(p0: Int) {
                launch {
                    withContext(Dispatchers.Main) {
                        x5Response.onDownloadProgress(1) {
                        }
                    }
                }
            }
        })
        QbSdk.initX5Environment(context?.applicationContext, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                launch {
                    withContext(Dispatchers.Main) {
                        x5Response.onCoreInitFinished(1) {
                        }
                    }
                }

            }

            override fun onViewInitFinished(p0: Boolean) {
                launch {
                    withContext(Dispatchers.Main) {
                        x5Response.onViewInitFinished(if (p0) 1 else 0) {}
                    }
                }
            }
        })
        QbSdk.setDownloadWithoutWifi(true)
    }

    fun openVideo(context: Context?, x5Response: X5Response, arguments: Map<String, Any>) {
        val url = arguments["url"] as? String ?: "";
        val screenMode = arguments["screenMode"] as? Int ?: 103;
        val bundle = Bundle()
        bundle.putInt("screenMode", screenMode)
        TbsVideo.openVideo(context, url, bundle)
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + Job()
}